package com.fire.communication.web.websocket;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.fire.communication.common.base.BaseService;
import com.fire.communication.config.websocket.SocketIOService;
import com.fire.communication.support.utils.MyLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能描述
 *
 * @author: zyu
 * @description:
 * @date: 2019/4/23 10:42
 */
@Service(value = "socketIOService")
public class SocketIOServiceImpl extends BaseService implements SocketIOService {

    // 用来存已连接的客户端
    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

    @Autowired
    private SocketIOServer socketIOServer;
    @Resource
    public MyLogger logger;

    /**
     * Spring IoC容器创建之后，在加载SocketIOServiceImpl Bean之后启动
     *
     * @throws Exception
     */
    @PostConstruct
    private void autoStartup() throws Exception {
        start();
    }

    /**
     * Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题
     *
     * @throws Exception
     */
    @PreDestroy
    private void autoStop() throws Exception {
        stop();
    }

    @Override
    public void start() throws Exception {
        // 监听客户端连接
        socketIOServer.addConnectListener(client -> {
            clientMap.put(UUID.randomUUID().toString().replace("-",""), client);
            System.out.println("初始化-------------------------------");
        });

        // 监听客户端断开连接
        socketIOServer.addDisconnectListener(client -> {
            System.out.println("断开连接");
        });

        // 处理自定义的事件，与连接监听类似
        socketIOServer.addEventListener("text", Object.class, (client, data, ackSender) -> {

        });

        socketIOServer.start();
    }



    @Override
    public void stop() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;
        }
    }

    @Override
    public void pushMessageToUser(String str) {
        System.out.println("clientMap-------------------------------"+clientMap.size()+"str"+str);
        Set<String> set = clientMap.keySet();
        if(set.size() > 0){
            for(String key : set){
                SocketIOClient client = clientMap.get(key);
                logger.info("client-------------------------------"+client);
                if (client != null) {
                    logger.info("SessionId:-----------  " + client.getSessionId());
                    logger.info("RemoteAddress:------------  " + client.getRemoteAddress());
                    logger.info("Transport:---------------  " + client.getTransport());
                    client.sendEvent(PUSH_EVENT, str);
                }
            }
        }
    }

    /**
     * 此方法为获取client连接中的参数，可根据需求更改
     * @param client
     * @return
     */
    private String getParamsByClient(SocketIOClient client) {
        // 从请求的连接中拿出参数（这里的loginUserNum必须是唯一标识）
        Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
        List<String> list = params.get("loginUserNum");
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    public static Map<String, SocketIOClient> getClientMap() {
        return clientMap;
    }

    public static void setClientMap(Map<String, SocketIOClient> clientMap) {
        SocketIOServiceImpl.clientMap = clientMap;
    }
}